# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2005-2006 CamptoCamp
# Copyright (c) 2006-2010 OpenERP S.A
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import os, time
from datetime import datetime, timedelta
from openerp.osv import osv, fields
from openerp.tools.translate import _
from openerp.report import report_sxw
import locale
from mx import DateTime as dt
from PIL.TiffImagePlugin import DATE_TIME
from mx.Tools.mxTools.mxTools import sign
from array import array
locale.setlocale(locale.LC_ALL, '')
from openerp.tools import float_round, float_is_zero, float_compare

class open_po_report(report_sxw.rml_parse):
    _name = 'open.po.report'

    def set_context(self, objects, data, ids, report_type=None):
        new_ids = ids
         
        val_part = []
        val_part.append(('state','=','approved'))
        date_from = data['form']['date_from']
        date_to = data['form']['date_to']

        if data['form']['date_selection'] == 'date_sel' :
            if date_from and not date_to:
                val_part.append(('date_order','>=',str(date_from)))
            elif date_to and not date_from:
                val_part.append(('date_order','<=',str(date_to))) 
            elif date_to and date_from:
                val_part.append(('date_order','>=',str(date_from)))
                val_part.append(('date_order','<=',str(date_to)))

        self.val_part = val_part
        self.date_from = date_from
        self.date_to = date_to
        report_type = data['form']['report_type']

        return super(open_po_report, self).set_context(objects, data, new_ids, report_type=report_type)

    def __init__(self, cr, uid, name, context=None):
        super(open_po_report, self).__init__(cr, uid, name, context=context)
        self.report_total = 0.00
        self.balance_by_cur = {}
        self.uid=uid
        self.localcontext.update({
            'time': time,
            'locale': locale,
            'get_lines': self._get_lines,
            'get_header_title': self._get_header, 
            'get_printed_date' : self._get_printed_date,
            'get_balance_by_cur': self._get_balance_by_cur,
            'get_search_date': self._get_search_date,
            'get_decimal_accuracy': self._get_decimal_accuracy,
            'get_printed_by': self._get_printed_by,
            })
 
    def _get_printed_date(self):
        header = ''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            tz = user_obj.browse(self.cr, self.uid, user_ids[0])
            tz_name = tz.tz
        os.environ['TZ'] = tz_name #set time zone secara otomatis tidak hard code
        time.tzset()
        header = 'Printed date : ' + time.strftime("%Y/%m/%d") + '  Time : '+ time.strftime("%H:%M:%S")
         
        return header
    
    def _get_printed_by(self):
        header =''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            user_id = user_obj.browse(self.cr, self.uid, user_ids[0])
            user_name = user_id.name
        
        header = 'Printed by : ' +user_name
        
        return header
    
    def _get_search_date(self):
        header = ''
        date_from = self.date_from
        date_to = self.date_to
        if date_from and not date_to:
            header='Date : From ' + str(date_from)
        elif date_to and not date_from:
            header='Date : Until ' + str(date_to)
        elif date_to and date_from:
             header='Date : ' + str(date_from) + ' - ' + str(date_to)
             
        return header
    
    def _get_decimal_accuracy(self):
        dp = 2
        dp_obj = self.pool.get('decimal.precision')
        dp_ids = dp_obj.search(self.cr, self.uid, [('name','=','Account')])
        if dp_ids :
            dp_id = dp_obj.browse(self.cr, self.uid, dp_ids[0])
            dp = dp_id.digits
        return dp    
    
    def _get_balance_by_cur(self):
        result = []
        currency_obj    = self.pool.get('res.currency') 
        for item in self.balance_by_cur.items():
            result.append({
                'cur_name' : currency_obj.browse(self.cr, self.uid, item[0]).name,
                'total_untaxed' : item[1]['total_untaxed'],
                'total_amount' : item[1]['total_amount'],
            })
        result = result and sorted(result, key=lambda val_res: val_res['cur_name']) or []
        return result
    
    def _get_header(self):
        header = 'Summary Open PO Report'
        return header
      
    def _get_lines(self):
        cr              = self.cr
        uid             = self.uid
        purchase_order_obj      = self.pool.get('purchase.order')
        stock_picking_obj     = self.pool.get('stock.picking')
        partner_obj     = self.pool.get('res.partner')
        company_obj = self.pool.get('res.company')
        currency_obj = self.pool.get('res.currency')
        purchase_orderline_obj    = self.pool.get('purchase.order.line')
        
        results1        = []
        val_part = self.val_part 
        
        purchase_order_ids=purchase_order_obj.search(cr, uid,val_part)
         
        for purchase_orderr in purchase_order_obj.browse(cr, uid, purchase_order_ids, context=None):
            if purchase_orderr.shipped_rate >= 100:
                continue
            if purchase_orderr.all_service:
                continue
            cur_id_part = purchase_orderr.currency_id.id  
   
            results1.append({
                    'po_no' : purchase_orderr.name,
                    'date_order' :purchase_orderr.date_order,
                    'partner_id': purchase_orderr.partner_id.name,
                    'minimum_planned_date' : purchase_orderr.minimum_planned_date,
                    'currency_id' : purchase_orderr.currency_id.name,
                    'amount_untaxed' : purchase_orderr.amount_untaxed,
                    'amount_total' : purchase_orderr.amount_total, 
                    })
                          
            if cur_id_part not in self.balance_by_cur:
                    self.balance_by_cur.update({cur_id_part : {
                             'total_untaxed' : (purchase_orderr.amount_untaxed),
                             'total_amount' : (purchase_orderr.amount_total),
                             }
                        })
            else:
                    res_currency_grouping = self.balance_by_cur[cur_id_part].copy()
                    res_currency_grouping['total_untaxed'] += (purchase_orderr.amount_untaxed)
                    res_currency_grouping['total_amount'] += (purchase_orderr.amount_total)
    
                    self.balance_by_cur[cur_id_part] = res_currency_grouping
        
        results1 = results1 and sorted(results1, key=lambda val_res: val_res['po_no']) or []
        return results1  
    
    
report_sxw.report_sxw('report.open.po.report', 'purchase.order',
'addons/batam_fast_module/purchase/report/report/open_po_report.rml', parser=open_po_report, header=False)
   
         
        
